<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="180px"
      v-loading="formLoading"
    >
      <el-form-item label="发货单号" prop="shipmentNo">
        <el-input v-model="formData.shipmentNo" placeholder="请输入发货单号" />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderId">
        <el-input v-model="formData.orderId" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>
      <el-form-item label="发货仓库编号" prop="warehouseId">
        <el-input v-model="formData.warehouseId" placeholder="请输入发货仓库编号" />
      </el-form-item>
      <el-form-item label="发货仓库名称" prop="warehouseName">
        <el-input v-model="formData.warehouseName" placeholder="请输入发货仓库名称" />
      </el-form-item>
      <el-form-item label="发货类型" prop="shipmentType">
        <el-select v-model="formData.shipmentType" placeholder="请选择发货类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_SHIPMENT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送方式" prop="shippingMethod">
        <el-input v-model="formData.shippingMethod" placeholder="请输入配送方式" />
      </el-form-item>
      <el-form-item label="配送服务" prop="shippingService">
        <el-input v-model="formData.shippingService" placeholder="请输入配送服务" />
      </el-form-item>
      <el-form-item label="承运商代码" prop="carrierCode">
        <el-input v-model="formData.carrierCode" placeholder="请输入承运商代码" />
      </el-form-item>
      <el-form-item label="承运商名称" prop="carrierName">
        <el-input v-model="formData.carrierName" placeholder="请输入承运商名称" />
      </el-form-item>
      <el-form-item label="运单号" prop="trackingNo">
        <el-input v-model="formData.trackingNo" placeholder="请输入运单号" />
      </el-form-item>
      <el-form-item label="跟踪链接" prop="trackingUrl">
        <el-input v-model="formData.trackingUrl" placeholder="请输入跟踪链接" />
      </el-form-item>
      <el-form-item label="发货总数量" prop="totalQuantity">
        <el-input v-model="formData.totalQuantity" placeholder="请输入发货总数量" />
      </el-form-item>
      <el-form-item label="总重量" prop="totalWeight">
        <el-input v-model="formData.totalWeight" placeholder="请输入总重量（kg）" />
      </el-form-item>
      <el-form-item label="总体积" prop="totalVolume">
        <el-input v-model="formData.totalVolume" placeholder="请输入总体积（立方米）" />
      </el-form-item>
      <el-form-item label="包裹数量" prop="packageCount">
        <el-input v-model="formData.packageCount" placeholder="请输入包裹数量" />
      </el-form-item>
      <el-form-item label="运费" prop="shippingCost">
        <el-input v-model="formData.shippingCost" placeholder="请输入运费" />
      </el-form-item>
      <el-form-item label="保险费" prop="insuranceCost">
        <el-input v-model="formData.insuranceCost" placeholder="请输入保险费" />
      </el-form-item>
      <el-form-item label="处理费" prop="handlingCost">
        <el-input v-model="formData.handlingCost" placeholder="请输入处理费" />
      </el-form-item>
      <el-form-item label="总费用" prop="totalCost">
        <el-input v-model="formData.totalCost" placeholder="请输入总费用" />
      </el-form-item>
      <el-form-item label="货币代码" prop="currencyCode">
        <el-input v-model="formData.currencyCode" placeholder="请输入货币代码" />
      </el-form-item>
      <el-form-item label="预计送达日期" prop="estimatedDeliveryDate">
        <el-date-picker
          v-model="formData.estimatedDeliveryDate"
          type="date"
          value-format="x"
          placeholder="选择预计送达日期"
        />
      </el-form-item>
      <el-form-item label="预计运输天数" prop="estimatedTransitDays">
        <el-input v-model="formData.estimatedTransitDays" placeholder="请输入预计运输天数" />
      </el-form-item>
      <el-form-item label="发货时间" prop="shipTime">
        <el-date-picker
          v-model="formData.shipTime"
          type="date"
          value-format="x"
          placeholder="选择发货时间"
        />
      </el-form-item>
      <el-form-item label="取件时间" prop="pickupTime">
        <el-date-picker
          v-model="formData.pickupTime"
          type="date"
          value-format="x"
          placeholder="选择取件时间"
        />
      </el-form-item>
      <el-form-item label="运输中时间" prop="inTransitTime">
        <el-date-picker
          v-model="formData.inTransitTime"
          type="date"
          value-format="x"
          placeholder="选择运输中时间"
        />
      </el-form-item>
      <el-form-item label="派送中时间" prop="outForDeliveryTime">
        <el-date-picker
          v-model="formData.outForDeliveryTime"
          type="date"
          value-format="x"
          placeholder="选择派送中时间"
        />
      </el-form-item>
      <el-form-item label="送达时间" prop="deliveryTime">
        <el-date-picker
          v-model="formData.deliveryTime"
          type="date"
          value-format="x"
          placeholder="选择送达时间"
        />
      </el-form-item>
      <el-form-item label="派送尝试次数" prop="deliveryAttempts">
        <el-input v-model="formData.deliveryAttempts" placeholder="请输入派送尝试次数" />
      </el-form-item>
      <el-form-item label="配送状态" prop="deliveryStatus">
        <el-radio-group v-model="formData.deliveryStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_DELIVERY_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="签收人" prop="deliverySignature">
        <el-input v-model="formData.deliverySignature" placeholder="请输入签收人" />
      </el-form-item>
      <el-form-item label="配送备注" prop="deliveryNotes">
        <el-input v-model="formData.deliveryNotes" placeholder="请输入配送备注" />
      </el-form-item>
      <el-form-item label="海关申报信息JSON" prop="customsDeclaration">
        <el-input v-model="formData.customsDeclaration" placeholder="请输入海关申报信息JSON" />
      </el-form-item>
      <el-form-item label="清关状态" prop="customsStatus">
        <el-radio-group v-model="formData.customsStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMS_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="清关跟踪号" prop="customsTrackingNo">
        <el-input v-model="formData.customsTrackingNo" placeholder="请输入清关跟踪号" />
      </el-form-item>
      <el-form-item label="是否投保" prop="isInsured">
        <el-radio-group v-model="formData.isInsured">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="保险金额" prop="insuranceAmount">
        <el-input v-model="formData.insuranceAmount" placeholder="请输入保险金额" />
      </el-form-item>
      <el-form-item label="是否需要签收" prop="isSignatureRequired">
        <el-radio-group v-model="formData.isSignatureRequired">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="特殊说明" prop="specialInstructions">
        <el-input v-model="formData.specialInstructions" placeholder="请输入特殊说明" />
      </el-form-item>
      <el-form-item label="装箱单URL" prop="packingSlipUrl">
        <el-input v-model="formData.packingSlipUrl" placeholder="请输入装箱单URL" />
      </el-form-item>
      <el-form-item label="运单标签URL" prop="shippingLabelUrl">
        <el-input v-model="formData.shippingLabelUrl" placeholder="请输入运单标签URL" />
      </el-form-item>
      <el-form-item label="发票URL" prop="invoiceUrl">
        <el-input v-model="formData.invoiceUrl" placeholder="请输入发票URL" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderShipmentApi, OrderShipmentVO } from '@/api/crossborder/ordershipment'
import { DICT_TYPE, getIntDictOptions, getBoolDictOptions } from '@/utils/dict'

/** 跨境电商订单发货 表单 */
defineOptions({ name: 'OrderShipmentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  shipmentNo: undefined,
  orderId: undefined,
  orderNo: undefined,
  warehouseId: undefined,
  warehouseName: undefined,
  shipmentType: undefined,
  shippingMethod: undefined,
  shippingService: undefined,
  carrierCode: undefined,
  carrierName: undefined,
  trackingNo: undefined,
  trackingUrl: undefined,
  totalQuantity: undefined,
  totalWeight: undefined,
  totalVolume: undefined,
  packageCount: undefined,
  shippingCost: undefined,
  insuranceCost: undefined,
  handlingCost: undefined,
  totalCost: undefined,
  currencyCode: undefined,
  estimatedDeliveryDate: undefined,
  estimatedTransitDays: undefined,
  shipTime: undefined,
  pickupTime: undefined,
  inTransitTime: undefined,
  outForDeliveryTime: undefined,
  deliveryTime: undefined,
  deliveryAttempts: undefined,
  deliveryStatus: undefined,
  deliverySignature: undefined,
  deliveryNotes: undefined,
  customsDeclaration: undefined,
  customsStatus: undefined,
  customsTrackingNo: undefined,
  isInsured: undefined,
  insuranceAmount: undefined,
  isSignatureRequired: undefined,
  specialInstructions: undefined,
  packingSlipUrl: undefined,
  shippingLabelUrl: undefined,
  invoiceUrl: undefined,
  remark: undefined,
})
const formRules = reactive({
  shipmentNo: [{ required: true, message: '发货单号不能为空', trigger: 'blur' }],
  orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '发货仓库编号不能为空', trigger: 'blur' }],
  warehouseName: [{ required: true, message: '发货仓库名称不能为空', trigger: 'blur' }],
  shipmentType: [{ required: true, message: '发货类型（1正常发货 2部分发货 3补发 4换货发货）不能为空', trigger: 'change' }],
  shippingMethod: [{ required: true, message: '配送方式不能为空', trigger: 'blur' }],
  totalQuantity: [{ required: true, message: '发货总数量不能为空', trigger: 'blur' }],
  packageCount: [{ required: true, message: '包裹数量不能为空', trigger: 'blur' }],
  shippingCost: [{ required: true, message: '运费不能为空', trigger: 'blur' }],
  insuranceCost: [{ required: true, message: '保险费不能为空', trigger: 'blur' }],
  handlingCost: [{ required: true, message: '处理费不能为空', trigger: 'blur' }],
  totalCost: [{ required: true, message: '总费用不能为空', trigger: 'blur' }],
  deliveryAttempts: [{ required: true, message: '派送尝试次数不能为空', trigger: 'blur' }],
  deliveryStatus: [{ required: true, message: '配送状态（10待发货 20已发货 30运输中 40派送中 50已送达 60配送失败 70已退回）不能为空', trigger: 'blur' }],
  isInsured: [{ required: true, message: '是否投保不能为空', trigger: 'blur' }],
  isSignatureRequired: [{ required: true, message: '是否需要签收不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderShipmentApi.getOrderShipment(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderShipmentVO
    if (formType.value === 'create') {
      await OrderShipmentApi.createOrderShipment(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderShipmentApi.updateOrderShipment(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    shipmentNo: undefined,
    orderId: undefined,
    orderNo: undefined,
    warehouseId: undefined,
    warehouseName: undefined,
    shipmentType: undefined,
    shippingMethod: undefined,
    shippingService: undefined,
    carrierCode: undefined,
    carrierName: undefined,
    trackingNo: undefined,
    trackingUrl: undefined,
    totalQuantity: undefined,
    totalWeight: undefined,
    totalVolume: undefined,
    packageCount: undefined,
    shippingCost: undefined,
    insuranceCost: undefined,
    handlingCost: undefined,
    totalCost: undefined,
    currencyCode: undefined,
    estimatedDeliveryDate: undefined,
    estimatedTransitDays: undefined,
    shipTime: undefined,
    pickupTime: undefined,
    inTransitTime: undefined,
    outForDeliveryTime: undefined,
    deliveryTime: undefined,
    deliveryAttempts: undefined,
    deliveryStatus: undefined,
    deliverySignature: undefined,
    deliveryNotes: undefined,
    customsDeclaration: undefined,
    customsStatus: undefined,
    customsTrackingNo: undefined,
    isInsured: undefined,
    insuranceAmount: undefined,
    isSignatureRequired: undefined,
    specialInstructions: undefined,
    packingSlipUrl: undefined,
    shippingLabelUrl: undefined,
    invoiceUrl: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>